package main

import (
	"fmt"
	"github.com/labstack/echo/v4"
	"net/http"
	"time"
)

func main() {
	e := echo.New()
	e.Use(Middleware)
	e.GET("/index", Index)
	e.GET("/chan", Chan)
	e.Start(":80")
}

func Index(c echo.Context) error {
	cc := c.(*CustomContext) //类型断言
	cc.Foo()
	cc.Bar()
	return c.String(http.StatusOK, "ok")
}

func Chan(c echo.Context) error {
	ca := make(chan string, 1)
	r := c.Request()
	method := r.Method

	go func() {
		fmt.Printf("Method: %s\n", method)
		time.Sleep(3 * time.Second)

		ca <- "Hey!"
	}()

	select { // select解决chan阻塞问题
	case result := <-ca:
		return c.String(http.StatusOK, result)
	case <-c.Request().Context().Done():
		return c.String(http.StatusOK, "timout")
	default:
		return c.String(http.StatusOK, "waiting")

	}

}

// CustomContext
// @Description: 定义一个自定义 context
type CustomContext struct {
	echo.Context //继承
}

func (c *CustomContext) Foo() {
	println("foo")
}

func (c *CustomContext) Bar() {
	println("bar")
}

// Middleware
//
//	@Description: 创建一个中间件来扩展默认的 context
//	@param next
//	@return echo.HandlerFunc
func Middleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		cc := &CustomContext{c}
		return next(cc)
	}
}
